package org.dousb.douojbackendjudgeservice.rabbitmq;


import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.dousb.douojbackendjudgeservice.judge.JudgeService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * MyMessageConsumer
 *
 * @author 豆沙包
 * @version 1.0
 * @since 2025-11-05  23:17
 */
@Slf4j
@Component
public class MyMessageConsumer {

    @Resource
    private JudgeService judgeService;

    /**
     * 使用@SneakyThrows注解简化异常处理，自动抛出受检异常
     * 使用@RabbitListener注解定义消息监听器，监听名为"code_queue"的队列
     * 设置ackMode为"MANUAL"，表示手动消息确认模式
     *
     * @param message     接收到的消息内容
     * @param channel     RabbitMQ通道对象，用于后续操作
     * @param deliveryTag 消息的投递标签，用于消息确认
     */
    @SneakyThrows
    @RabbitListener(queues = {"code_queue"}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        // 记录接收到的消息日志
        log.info("接收到消息: {}", message);
    // 将消息内容转换为Long类型，作为题目提交ID
        long questionSubmitId = Long.parseLong(message);
        try {
            // 调用judgeService的doJudge方法进行判题处理
            judgeService.doJudge(questionSubmitId);
            // 手动确认消息，deliveryTag为消息标识，false表示只确认当前消息
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            channel.basicNack(deliveryTag, false, false);
        }
    }
}